package com.hengxinguotong.zhihuichengjian.ui.building;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AccidentAddPersonAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.EnterpriseConstructionAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.EnterpriseUserAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Construction;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/1/10
 */

public class NoticeAddActivity extends BaseActivity implements View.OnClickListener, AualityTestAddPicAdapter.OnRecyclerViewClickListener {
    private static final int ADD_CONTACT = 0;
    private static final int ADD_NOTICE = 1;
    private static final int ADD_PIC = 2;

    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.title_etv)
    HXEditTextView titleEtv;
    @BindView(R.id.content_etv)
    HXEditTextView contentEtv;
    @BindView(R.id.notice_rv)
    RecyclerView noticeRv;
    @BindView(R.id.pic_rv)
    RecyclerView picRv;

    private List<User> noticedPersons, selectNotices;//告知人员数组
    private AccidentAddPersonAdapter noticeAdapter;
    private boolean fromEnterprise = false;
    private List<Construction> noticeConstructions;
    private EnterpriseConstructionAdapter noticeEnterpriseAdapter;

    private List<String> paths;
    private List<String> minPaths;
    private AualityTestAddPicAdapter aualityTestAddPicAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notice_add);
        fromEnterprise = getIntent().getBooleanExtra("fromEnterprise", false);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        titleTv.setText("通知公告新增");
        selectNotices = new ArrayList<>();
        if(fromEnterprise){
            noticeConstructions = new ArrayList<>();
            noticeEnterpriseAdapter = new EnterpriseConstructionAdapter(this, noticeConstructions);
            noticeEnterpriseAdapter.setOnChildDeleteClickListener(noticeDelete);
            noticeEnterpriseAdapter.setOnChildHeadClickListener(noticeHead);
            noticeEnterpriseAdapter.setHasDelete(true);
            noticeRv.setAdapter(noticeEnterpriseAdapter);
            noticeRv.setLayoutManager(getVerticalLinearLayoutManager());
        }else {
            noticedPersons = new ArrayList<User>();
            noticedPersons.add(getAddUser());
            noticeAdapter = new AccidentAddPersonAdapter(this, noticedPersons, new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                @Override
                public void onItemClick(View v, int position) {
                    if (Utils.ADDPIC.equals(noticedPersons.get(position).getHeadPortrait())) {
                        goToNotices();
                    } else {
                        User user = noticedPersons.get(position);
                        noticedPersons.remove(user);
                        selectNotices.remove(user);
                        noticeAdapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void onClick(View v) {

                }
            }, true);
            noticeRv.setLayoutManager(getLinearLayoutManager());
            noticeRv.setAdapter(noticeAdapter);
        }

        paths = new ArrayList<String>();
        paths.add(Utils.ADDPIC);
        aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
        picRv.setLayoutManager(getLinearLayoutManager());
        picRv.setAdapter(aualityTestAddPicAdapter);
    }

    private void goToNotices() {
        Intent intent = new Intent();
        if(fromEnterprise){
            intent.setClass(NoticeAddActivity.this, EnterpriseUserSelectActivity.class);
            intent.putExtra("fromNotice", true);
        }else {
            intent.setClass(NoticeAddActivity.this, ConstructionUserSelectActivity.class);
        }
        intent.putExtra("noticedPersons", (Serializable) selectNotices);
        startActivityForResult(intent, ADD_NOTICE);
    }

    private LinearLayoutManager getVerticalLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        return linearLayoutManager;
    }

    private EnterpriseUserAdapter.OnChildDeleteClickListener noticeDelete = new EnterpriseUserAdapter.OnChildDeleteClickListener() {
        @Override
        public void onChildDeleteClick(int position, int childPosition) {
            User user = noticeConstructions.get(position).getUserList().get(childPosition);
            noticeConstructions.get(position).getUserList().remove(user);
            selectNotices.remove(user);
            if(noticeConstructions.get(position).getUserList().size() <= 0){
                noticeConstructions.remove(position);
            }
            noticeEnterpriseAdapter.setDataList(noticeConstructions);
        }
    };

    private  EnterpriseUserAdapter.OnChildHeadClickListener noticeHead = new EnterpriseUserAdapter.OnChildHeadClickListener() {
        @Override
        public void onChildHeadClick(int position, int childPosition) {
            String headPotrait = noticeConstructions.get(position).getUserList().get(childPosition).getHeadPortrait();
            if(!Utils.isEmpty(headPotrait)){
                List<String> picList = new ArrayList<>();
                picList.add(headPotrait);
                TaskBigImgActivity.startActivity(NoticeAddActivity.this, (ArrayList<String>) picList, position);
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            switch (requestCode){
                case ADD_PIC:
                    paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    paths.add(Utils.ADDPIC);
                    if (aualityTestAddPicAdapter != null) {
                        aualityTestAddPicAdapter.setPaths(paths);
                    }
                    break;
                case ADD_NOTICE:
                    if(fromEnterprise){
                        List<User> noticeTemp = (List<User>) data.getSerializableExtra("selectUsers");
                        for (int i = 0; i < noticeTemp.size(); i++) {
                            User user = noticeTemp.get(i);
                            if (!user.isInUsers(selectNotices)) {
                                selectNotices.add(user);
                            }
                        }
                        List<Construction> noticeConstructionTemp = (List<Construction>) data.getSerializableExtra("selectConstructions");
                        for (Construction construction:noticeConstructionTemp){
                            List<User> u1 = construction.getUserList();
                            for (User user:selectNotices){
                                if(user.getConstructionId().equals(construction.getConstructionId())){
                                    u1.add(user);
                                }
                            }
                        }
                        noticeConstructions = noticeConstructionTemp;
                        noticeEnterpriseAdapter.setDataList(noticeConstructions);
                    }else {
                        List<User> noticeTemp = (List<User>) data.getSerializableExtra("selectNoticers");
                        for (int i = 0; i < noticeTemp.size(); i++) {
                            User user = noticeTemp.get(i);
                            if (!user.isInUsers(selectNotices)) {
                                selectNotices.add(user);
                            }
                        }
                        noticeConstructions = new ArrayList<>();
                        Construction construction = new Construction();
                        construction.setConstructionId(SPUtil.getString(this, "constructionid"));
                        construction.setUserList(selectNotices);
                        noticedPersons.clear();
                        noticedPersons.add(getAddUser());
                        noticedPersons.addAll(selectNotices);
                        noticeAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    @OnClick({R.id.iv_back, R.id.save_test, R.id.notice_tv})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_test:
                getMinImage();
                break;
            case R.id.notice_tv:
                goToNotices();
                break;
        }
    }

    private void getMinImage() {
        if (!checkContent()) {
            return;
        }

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    addTest();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            addTest();
        }

    }

    private void addTest() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("title", titleEtv.getEditableText().toString());
        params.addBodyParameter("content", contentEtv.getEditableText().toString());

        if(selectNotices != null && selectNotices.size()>0){
            JSONArray cArray = new JSONArray();
            for (Construction construction:noticeConstructions){
                try {
                    JSONObject cObject = new JSONObject();
                    cObject.put("constructionId", construction.getConstructionId());
                    JSONArray uArray = new JSONArray();
                    for(int i=0;i<construction.getUserList().size();i++) {
                        JSONObject uObject = new JSONObject();
                        uObject.put("acceptId",construction.getUserList().get(i).getUserId());
                        uObject.put("status",construction.getUserList().get(i).getStatus());
                        uArray.put(uObject);
                    }
                    cObject.put("acceptInfoList", uArray);
                    cArray.put(cObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            params.addBodyParameter("acceptList", cArray.toString());
        }

        for (int i = 0; i < minPaths.size(); i++) {
            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
        }

        params.addBodyParameter("createBy", SPUtil.getString(this, "userId"));

        Utils.requestData(getResources().getString(R.string.loading), this, "/notice/batchAdd/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    if(status == 1){
                        showToast("提交成功");
                        setResult(RESULT_OK);
                        finish();
                    }else {
                        String msg = object.getString("msg");
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });

    }

    private boolean checkContent() {
        if (Utils.isEmpty(titleEtv.getEditableText().toString())) {
            showToast("请填写标题");
            return false;
        }

        if (Utils.isEmpty(contentEtv.getEditableText().toString())) {
            showToast("请填写内容");
            return false;
        }

        if(selectNotices.size() <= 0){
            showToast("请选择消息接收人");
            return false;
        }

//        if(minPaths.size() <= 0){
//            showToast("请选择附件");
//            return false;
//        }

        return true;
    }

    private User getAddUser() {
        User addUser = new User();
        addUser.setHeadPortrait(Utils.ADDPIC);
        addUser.setUserId("-1");
        addUser.setName("");
        return addUser;
    }

    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, ADD_PIC);
        } else {
            paths.remove(position);
            aualityTestAddPicAdapter.notifyDataSetChanged();
        }
    }
}
